package com.crazyhat.crazyhat.interceptors;

import java.util.Map;

import com.crazyhat.crazyhat.utils.TokenBlacklistUtil;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.crazyhat.crazyhat.utils.JwtUtil;
import com.crazyhat.crazyhat.utils.ThreadLocalUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptors implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        /*
         * 使用Authorization请求头标识用户是否登录，
         * 并将解码后的token信息存储到ThreadLocal供后续使用
         */

        //拦截所有未登录用户的访问请求
        String token = request.getHeader("Authorization");
        try {
            if (TokenBlacklistUtil.isTokenBlacklisted(token)) {
                response.setStatus(401);
                return false;
            }

            Map<String, Object> claims = JwtUtil.parseToken(token);

            // 将业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);

            return true;

        } catch (Exception e) {

            TokenBlacklistUtil.removeFromBlacklist(token); // 删除无效的 token

            response.setStatus(401);

            return false;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {

        //移除存储在ThreadLocal的信息
        ThreadLocalUtil.remove();
    }
}
